package com.chengzzz.mysite.realm;



import com.chengzzz.mysite.entity.User;
import com.chengzzz.mysite.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * CustomRealm
 * </p>
 *
 * @author 等什么柠檬君
 * @since 2020/8/10
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService accountService;


    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=====认证=====");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println(token.getUsername());
        System.out.println("这是shiro获取的email"+token.getUsername());
        User user = accountService.findUserByEmail(token.getUsername());
        if(user != null){
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return null;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("=====授权=====");
        /**
         *
         * @param principalCollection principalCollection
         * @return org.apache.shiro.authz.AuthorizationInfo
         * @author 等什么柠檬君
         * @since 2020/8/10
         * @description    获取当前用户
         */
        Subject subject = SecurityUtils.getSubject();
        User user  = (User) subject.getPrincipal();
        /**
         *
         * @param principalCollection principalCollection
         * @return org.apache.shiro.authz.AuthorizationInfo
         * @author 等什么柠檬君
         * @since 2020/8/10
         * @description    设置角色
         */
        Set<String> roles = new HashSet<>();
        roles.add(user.getRoles());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        /*设置权限*/
        info.addStringPermission(user.getPerms());
        return info;
    }





}